"""
应用初始化
"""
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_login import LoginManager
import logging
from logging.handlers import RotatingFileHandler
import os
from datetime import datetime
from app.config import config

# 初始化扩展
db = SQLAlchemy()
login_manager = LoginManager()
login_manager.login_view = 'auth.login'
login_manager.login_message = '请先登录再访问此页面'
login_manager.login_message_category = 'info'

def create_app(config_name='default'):
    """创建并配置Flask应用实例"""
    app = Flask(__name__)
    
    # 从配置文件加载配置
    app.config.from_object(config[config_name])
    config[config_name].init_app(app)
    
    # 初始化扩展
    db.init_app(app)
    login_manager.init_app(app)
    
    # 配置日志
    if not os.path.exists('logs'):
        os.mkdir('logs')
    # 配置文件日志
    file_handler = RotatingFileHandler('logs/zhiyi.log', maxBytes=10240, backupCount=5, encoding='utf-8')
    file_handler.setFormatter(logging.Formatter(
        '%(asctime)s %(levelname)s: %(message)s [在 %(pathname)s:%(lineno)d]'
    ))
    file_handler.setLevel(logging.INFO)
    app.logger.addHandler(file_handler)
    app.logger.setLevel(logging.INFO)
    
    app.logger.info('知疑问答社区启动成功')
    
    # 注册蓝图
    from app.controllers.main import main as main_blueprint
    app.register_blueprint(main_blueprint)

    from app.controllers.auth import auth as auth_blueprint
    app.register_blueprint(auth_blueprint, url_prefix='/auth')
    
    from app.controllers.question import question as question_blueprint
    app.register_blueprint(question_blueprint, url_prefix='/question')
    
    from app.controllers.user import user as user_blueprint
    app.register_blueprint(user_blueprint, url_prefix='/user')
    
    # 注册错误处理函数
    from app.controllers.errors import errors as errors_blueprint
    app.register_blueprint(errors_blueprint)
    
    # 注册自定义命令
    from app.commands import register_commands
    register_commands(app)
    
    # 注册上下文处理器
    from app.utils import DateUtil
    
    @app.context_processor
    def utility_processor():
        """装饰器: Flask上下文处理器，用于在所有模板中提供日期处理工具函数"""
        return {
            'time_ago': DateUtil.time_ago,
            'format_datetime': DateUtil.format_datetime,
            'now': lambda format: DateUtil.format_datetime(datetime.utcnow(), format)
        }
    
    return app 